package com.xxlie.auth.common;

import com.xxlie.auth.domain.User;
import com.xxlie.auth.security.model.UserContext;
import com.xxlie.core.exception.BusinessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xxlie.com
 * @since 2017/7/30
 */
public class UserLoginContext {

    /**
     * 获取当前登录用户
     *
     * @return 用户 {@link User}
     */
    public static User getCurrentUser() {

        SecurityContextImpl securityContext = (SecurityContextImpl) SecurityContextHolder.getContext();
        Authentication auth = securityContext.getAuthentication();
        UserContext context = (UserContext) auth.getPrincipal();
        if (context != null) {
            if (auth.getPrincipal().equals("anonymousUser")) {
                throw new BusinessException("未登录");
            }
            return context.getUser();
        }
        throw new BusinessException("未登录");
    }

    /**
     * 获取缓存对象
     *
     * @param key 缓存key
     * @return 缓存对象
     */
    public static Object getCache(String key) {
        return getCache(key, null);
    }

    public static Object getCache(String key, Object defaultValue) {
        Object obj = getCacheMap().get(key);
        return obj == null ? defaultValue : obj;
    }

    public static Map<String, Object> getCacheMap() {
        Map<String, Object> map = new HashMap<>();
        UserContext principal = (UserContext) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return principal != null ? principal.getCacheMap() : map;
    }

}
